/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-7-14 下午1:49
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.jdmetro.activities.life;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.dqhl.jdmetro.R;
import com.example.dqhl.jdmetro.adapter.life.LifeDetailCommentAdapter;
import com.example.dqhl.jdmetro.base.BaseActivity;
import com.example.dqhl.jdmetro.bean.life.LifeDetail;
import com.example.dqhl.jdmetro.bean.life.LifeDetailComment;
import com.example.dqhl.jdmetro.config.Config;
import com.example.dqhl.jdmetro.utils.Dlog;
import com.example.dqhl.jdmetro.utils.JsonUtils;
import com.example.dqhl.jdmetro.utils.Toastutils;
import com.example.dqhl.jdmetro.utils.recycleview.ConsulationRecycleViewLayoutManager;
import com.example.dqhl.jdmetro.widget.CallConfirmDialog;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * description:商家详情
 * autour:guanluocang
 * date:17/7/14 13:51
 */
public class LifeDetailActivity extends BaseActivity {

    @Bind(R.id.life_refresh_layout)
    TwinklingRefreshLayout life_refresh_layout;
    private final static int REQUEST_CODE_PERMISSION_CALL = 123;
    private Context context;
    @Bind(R.id.iv_top_back)
    ImageView iv_top_back;
    @Bind(R.id.tv_top_title)
    TextView tv_top_title;
    @Bind(R.id.iv_top_msg)
    ImageView iv_top_msg;

    @Bind(R.id.iv_lifePic)
    ImageView iv_lifePic;
    @Bind(R.id.tv_lifeSecondtitle)
    TextView tv_lifeSecondtitle;
    @Bind(R.id.tv_lifeaddress)
    TextView tv_lifeaddress;
    @Bind(R.id.tv_lifeDistance)
    TextView tv_lifeDistance;
    @Bind(R.id.tv_lifePageViews)
    TextView tv_lifePageViews;
    @Bind(R.id.tv_title)
    TextView tv_title;
    @Bind(R.id.tv_location)
    TextView tv_location;

    private Double latitude;
    private Double longitude;
    private String shop_id;

    @Bind(R.id.iv_callPhone)
    ImageView iv_callPhone;

    private String telPhone = "";//电话
    private int is_collect;

    //评论RecycleView
    @Bind(R.id.rv_life_detail_comment)
    RecyclerView rv_life_detail_comment;
    private LifeDetailCommentAdapter lifeDetailCommentAdapter;
    private List<LifeDetailComment.DataBean> consulationComments = new ArrayList<>();

    @Bind(R.id.tv_noInfo)
    TextView tv_noInfo;

    @Bind(R.id.et_speakContent)
    EditText et_speakContent;//评论内容
    @Bind(R.id.tv_sendMsg)
    TextView tv_sendMsg;//发送按钮
    private int page = 1;

    @Override
    public void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_life_detail);
        context = this;
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {

        tv_top_title.setText(R.string.txt_shop_detail);
        shop_id = getIntent().getStringExtra("shop_id");
        latitude = getIntent().getDoubleExtra("latitude", 0);
        longitude = getIntent().getDoubleExtra("longitude", 0);
        Dlog.e(latitude + " " + longitude);
        ConsulationRecycleViewLayoutManager layoutManager = new ConsulationRecycleViewLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_life_detail_comment.setLayoutManager(layoutManager);
        rv_life_detail_comment.setItemAnimator(new DefaultItemAnimator());
        rv_life_detail_comment.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        rv_life_detail_comment.setNestedScrollingEnabled(false);
        ProgressLayout headerView = new ProgressLayout(this);
        life_refresh_layout.setHeaderView(headerView);
        life_refresh_layout.setOverScrollRefreshShow(false);
//        rv_life_detail_comment.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
//        rv_life_detail_comment.setLoadingMoreProgressStyle(ProgressStyle.Pacman);
//        rv_life_detail_comment.setArrowImageView(R.drawable.iconfont_downgrey);
        doData();
        doCommentList(page);
    }

    private void doData() {
        RequestParams params = new RequestParams(Config.life_detail_content);
        params.addBodyParameter("shop_id", shop_id);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("latitude", latitude + "");
        params.addBodyParameter("longitude", longitude + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 200) {
                    LifeDetail lifeDetail = new Gson().fromJson(result, LifeDetail.class);
                    x.image().bind(iv_lifePic, Config.pic_base_url + lifeDetail.getData().getShop_logo());
                    tv_lifeSecondtitle.setText(lifeDetail.getData().getShop_text());
                    tv_lifeaddress.setText(lifeDetail.getData().getShop_city());
                    tv_lifeDistance.setText(lifeDetail.getData().getDistance());
                    telPhone = lifeDetail.getData().getShop_tel();
                    tv_lifePageViews.setText(lifeDetail.getData().getShop_pageviews() + "");
                    tv_title.setText(lifeDetail.getData().getShop_name());
                    tv_location.setText(lifeDetail.getData().getShop_address());

                    // 0 微收藏 1  已收藏
                    if (lifeDetail.getData().getIs_collect() == 0) {
                        iv_top_msg.setImageResource(R.drawable.ic_life_collect);
                        is_collect = 1;
                    } else {
                        iv_top_msg.setImageResource(R.drawable.ic_life_collect_pressed);
                        is_collect = 2;
                    }

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void initListener() {
        iv_top_back.setOnClickListener(this);
        iv_top_msg.setOnClickListener(this);
        tv_sendMsg.setOnClickListener(this);
        iv_callPhone.setOnClickListener(this);
        life_refresh_layout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                page = 1;
                doCommentList(page);
                refreshLayout.finishRefreshing();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                page++;
                loadMoreData(page);
                refreshLayout.finishLoadmore();
            }
        });
    }

    /**
     * 获取更多结果
     */
    public void loadMoreData(int pages) {
        Dlog.e(pages + "");
        RequestParams params = new RequestParams(Config.life_detail_comment);
        params.addBodyParameter("shop_id", shop_id);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("page", pages + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 200) {
                    LifeDetailComment lifeDetailComment = new Gson().fromJson(result, LifeDetailComment.class);
                    consulationComments.addAll(lifeDetailComment.getData());
                    rv_life_detail_comment.setAdapter(lifeDetailCommentAdapter);
                    lifeDetailCommentAdapter.notifyDataSetChanged();
                } else {
                    Toastutils.show("暂无评论");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取评论列表
     */
    public void doCommentList(int pages) {
        RequestParams params = new RequestParams(Config.life_detail_comment);
        params.addBodyParameter("shop_id", shop_id);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("page", pages + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 200) {
                    LifeDetailComment lifeDetailComment = new Gson().fromJson(result, LifeDetailComment.class);
                    if (lifeDetailComment.getData().size() == 0 || lifeDetailComment.getData() == null) {
                        tv_noInfo.setVisibility(View.VISIBLE);
                        rv_life_detail_comment.setVisibility(View.GONE);
                    } else {
                        tv_noInfo.setVisibility(View.GONE);
                        rv_life_detail_comment.setVisibility(View.VISIBLE);
                        consulationComments = lifeDetailComment.getData();
                        lifeDetailCommentAdapter = new LifeDetailCommentAdapter(context, consulationComments, new LifeDetailCommentAdapter.OnFabulousListener() {
                            @Override
                            public void onFabulous(int position) {
                                doFabulous(position);
                            }
                        }, new LifeDetailCommentAdapter.OnDeleteListener() {
                            @Override
                            public void onDelete(int position) {
                                doDelete(position);
                            }
                        });
                        rv_life_detail_comment.setAdapter(lifeDetailCommentAdapter);
                        lifeDetailCommentAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 点赞
     */

    public void doFabulous(int position) {
        showLoadingBar("");
        final RequestParams params = new RequestParams(Config.life_detail_comment_fabulous);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("shop_comment_id", consulationComments.get(position).getId());
        // 赞的状态：0-未赞，1-已赞
        if (consulationComments.get(position).getIs_comment_like_count() == 1) {
            params.addBodyParameter("state", 2 + "");
        } else {
            params.addBodyParameter("state", 1 + "");
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("点赞" + result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 200) {
                    doCommentList(page);
                    lifeDetailCommentAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideLoadingBar();
            }
        });
    }

    /**
     * 删除
     */
    public void doDelete(int position) {
        Dlog.e("GG" + consulationComments.get(position).getComment_id_auth());
        Dlog.e("GG" + user.getId_auth());
        if (consulationComments.get(position).getComment_id_auth().equals(user.getId_auth())) {
            showLoadingBar("");
            final RequestParams params = new RequestParams(Config.life_detail_comment_delete);
            params.addBodyParameter("id_auth", user.getId_auth());
            params.addBodyParameter("comment_id", consulationComments.get(position).getId());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("删除" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    if (errCode == 200) {
                        doCommentList(page);
                        lifeDetailCommentAdapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideLoadingBar();
                }
            });
        } else {
            Toastutils.show("只可删除私有评论");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            //收藏
            case R.id.iv_top_msg:
                doCollect();
                break;
            //打电话
            case R.id.iv_callPhone:
                if ("".equals(telPhone)) {
                    Toastutils.show("电话为空");
                } else {
                    contactCustomerService();
                }
                break;
            //进行评论
            case R.id.tv_sendMsg:
                doSendMsg();
                break;
        }
    }

    //发表评论
    private void doSendMsg() {
        String msg = et_speakContent.getText().toString().trim();
        if (!TextUtils.isEmpty(msg)) {
            RequestParams params = new RequestParams(Config.life_detail_comment_send);
            params.addBodyParameter("shop_id", shop_id);
            params.addBodyParameter("id_auth", user.getId_auth());
            params.addBodyParameter("comment_content", msg);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("评论成功" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    if (errCode == 200) {
                        et_speakContent.setText("");
                        InputMethodManager imm1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm1.hideSoftInputFromWindow(et_speakContent.getWindowToken(), 0);//从控件所在的窗口中隐藏
                        page = 1;
                        doCommentList(page);
                        lifeDetailCommentAdapter.notifyDataSetChanged();

                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        } else {
            Toastutils.show("请输入内容");
        }
    }

    /**
     * 收藏
     */
    private void doCollect() {
        RequestParams params = new RequestParams(Config.life_detail_collect);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("shop_id", shop_id);
        params.addBodyParameter("state", is_collect + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    int collects = Integer.parseInt(JsonUtils.getInfo(data, "is_collect"));
                    // 0 微收藏 1  已收藏
                    if (collects == 0) {
                        iv_top_msg.setImageResource(R.drawable.ic_life_collect);
                        is_collect = 1;
                    } else {
                        iv_top_msg.setImageResource(R.drawable.ic_life_collect_pressed);
                        is_collect = 2;
                    }

                } else {

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void contactCustomerService() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) !=
                PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, new String[]{"android.permission.CALL_PHONE"},
                        REQUEST_CODE_PERMISSION_CALL);
            }
        } else {
            CallConfirmDialog callConfirmDialog = new CallConfirmDialog(this, telPhone);
            callConfirmDialog.show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE_PERMISSION_CALL) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                CallConfirmDialog callConfirmDialog = new CallConfirmDialog(this, telPhone);
                callConfirmDialog.show();
            } else {
                Toastutils.show("请在设置中打开拨打电话的权限");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
